package com.zjcode.cdcer.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSONObject;
import com.chinatechstar.component.commons.entity.MPage;
import com.chinatechstar.component.commons.enums.Nation;
import com.chinatechstar.component.commons.result.PaginationBuilder;
import com.chinatechstar.component.commons.service.AliyunOssService;
import com.chinatechstar.component.commons.service.BaseService;
import com.chinatechstar.component.commons.supports.PageData;
import com.chinatechstar.component.commons.utils.ExcelUtils;
import com.chinatechstar.component.commons.utils.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.zjcode.cdcer.config.MConsts;
import com.zjcode.cdcer.mapper.CerSysteminitImportInfoMapper;
import com.zjcode.cdcer.mapper.SequenceMapper;
import com.zjcode.cdcer.mapper.TkmSysOrgMapper;
import com.zjcode.cdcer.mapper.ZjcodePhysicalExaminationInfoMapper;
import com.zjcode.cdcer.model.*;
import com.zjcode.cdcer.model.basic.JsonObj;
import com.zjcode.cdcer.model.excel.SelfTestTableVo;
import com.zjcode.cdcer.model.excel.SysteminitImportInfo;
import com.zjcode.cdcer.pojo.CerSysteminitImportInfo;
import com.zjcode.cdcer.service.*;
import com.zjcode.cdcer.utils.ExcelUtil;
import com.zjcode.cdcer.utils.RedisUtils;
import com.zjcode.cdcer.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CerSysteminitImportInfoServiceImpl implements CerSysteminitImportInfoService,
                                                           BaseService {

    @Autowired
    private CerSysteminitImportInfoMapper cerSysteminitImportInfoMapper;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private TkmSysUserService tkmSysUserService;

    @Autowired
    private TkmSysOrgService tkmSysOrgService;

    @Autowired
    private TkmSysOrgMapper orgMapper;

    @Autowired
    private CerPersonInfoService cerPersonInfoService;

    @Autowired
    private TkmEndoscopeDiagnoseNounInfoService endoscopeDiagnoseNounInfoService;

    @Autowired
    private CerTreatmentInfoService cerTreatmentInfoService;

    @Autowired
    private FollowUpListService followUpListService;

    @Autowired
    private SequenceMapper sequenceMapper;
    @Value("${studio.cer-personinfo-file-in-disk}")
    private String cerPersonFileInDisk;

    @Autowired
    private AliyunOssService aliyunOssService;
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private ZjcodePhysicalExaminationInfoMapper physicalExaminationInfoMapper;

    @Autowired
    private ZjcodeSelfTestInfoService zjcodeSelfTestInfoService;

    @Override
    public Map<String, Object> listAllTableData(PageData pageData) {
        String userId = (String) pageData.get("user");
        String extFlag = sysUserService.findUserExtFlag(userId);
        pageData.put("extFlag", extFlag);
        pageData.put("idsData", null);

        TkmUserOrgAndRegions regionsAndOrg = tkmSysUserService.findUserRegionsAndOrg(userId);

        // 读取区域信息
        pageData = Utils.transitionRegionInfo(pageData);

        MPage mPage = getPageInfo(pageData);
        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
        Map<String, List<SysDict>> keyListMap = allCerDicts
            .stream()
            .collect(Collectors.groupingBy(SysDict::getDictType));
        Page<Object> page = PageHelper.startPage(mPage.getCurrentPage(), mPage.getPageSize());
        List<LinkedHashMap<String, Object>> mapList = cerSysteminitImportInfoMapper.listAllTableData(
            pageData);

        keyListMap
            .entrySet()
            .parallelStream()
            .forEach(entry -> {
                // key
                String key = entry.getKey();
                if (key.equals("xb_code")) {
                    key = "sex";
                }
                List<SysDict> dicts = entry.getValue();
                String finalKey = key;
                mapList
                    .stream()
                    .forEach(map -> {
                        Object o = map.get(finalKey);
                        if (o != null) {
                            Optional<SysDict> first = dicts
                                .stream()
                                .filter(sysDict -> sysDict
                                    .getDictValue()
                                    .equals(o.toString()))
                                .findFirst();
                            first.ifPresent(sysDict -> {
                                map.put(finalKey, sysDict.getDictName());
                            });
                        }
                    });
            });

        // 还原内镜诊断
        mapList
            .parallelStream()
            .forEach(map -> {
                String njzd = (String) map.get("njzd");
                if (StringUtils.isEmpty(njzd)) {
                    return;
                }
                List<String> ids = Arrays.asList(njzd.split(","));
                List<TkmEndoscopeDiagnoseNounInfo> nounInfos = endoscopeDiagnoseNounInfoService.selectByNounIds(
                    ids);
                if (nounInfos != null) {
                    map.put("njzd",
                            nounInfos
                                .stream()
                                .map(each -> each.getName())
                                .collect(Collectors.joining(",")));
                } else {
                    map.put("njzd", "");
                }
            });

        // 身份证, 给身份证加上掩码
//        mapList
//            .parallelStream()
//            .forEach(each -> {
//                String sfz = (String) each.get("sfz");
//                if (sfz != null) {
//                    each.put("sfz", sfz.substring(0, 6) + "********" + sfz.substring(14));
//                }
//            });
        mapList.forEach(item -> {
            if (item.get("org_id") != null) {
                item.put("org_id", item.get("org_id").toString());
            }
        });

        return PaginationBuilder.buildResult(mapList,
                                             page.getTotal(),
                                             mPage.getCurrentPage(),
                                             mPage.getPageSize());
    }

    @Override
    public JsonObj batchDeletion(PageData pageData) {
        String tradeId = get32UUID();
        log.info("初始数据库临时库,批量删除数据开始, tradeId: {}", tradeId);
        String data = String.valueOf(pageData.get("data"));
        String[] ids = data.split("\\|");
        if (ids.length > 0) {
            cerSysteminitImportInfoMapper.deleteByIdIn(Arrays.asList(ids));
        }
        log.info("初始数据库临时库,批量删除数据结束, tradeId: {},一共删除数据:{}",
                 tradeId,
                 ids.toString());
        return JsonObj.success("删除成功");
    }

    @Override
    public JsonObj oneClickDelete(PageData pageData) {
        String tradeId = get32UUID();
        String userId = (String) pageData.get("user");
        String extFlag = sysUserService.findUserExtFlag(userId);

        log.info("初始数据库临时库,一键删除开始, tradeId: {}", tradeId);
        CerSysteminitImportInfo info = new CerSysteminitImportInfo();
        info.setIsUplpadTimeout(0);
        info.setIsUploaded(0);
        info.setDeleted(0);
        info.setExtFlag(extFlag);
        List<CerSysteminitImportInfo> list = cerSysteminitImportInfoMapper.queryByAll(info);
        // 获取出所有id组成的list
        List<String> ids = list
            .stream()
            .map(each -> each.getId())
            .collect(Collectors.toList());
        // 删除ids对应的数据
        if (!CollectionUtils.isEmpty(ids)) {
            int i = cerSysteminitImportInfoMapper.deleteByIdIn(ids);
            log.info("初始数据库临时库,一键删除了执行完成,{}条数据被删除,tradeId:{}", i, tradeId);
        }
        return JsonObj.success("删除成功");
    }

    @Override
    public List<CerSysteminitImportInfo> getAllNoErrorData(PageData pageData) {
        // 查询没有错误的数据,没有被标记超时的数据,没有上报的数据
        List<CerSysteminitImportInfo> data = cerSysteminitImportInfoMapper.getAllNoErrorData(
            pageData);
        if (CollectionUtils.isEmpty(data)) {
            data = new ArrayList<>();
        }
        return data;
    }

    @Override
    public void updateCerSysteminitImportInfoStatus(PageData pageData) {
        // 标记删除
        pageData.put("deleted", 1);
        // 标记数据无错
        pageData.put("isHaveError", 0);
        // 没有超时上报
        pageData.put("is_uplpad_timeout", 0);
        // 是否上报正式库
        pageData.put("is_uploaded", 1);

        cerSysteminitImportInfoMapper.updateCerSysteminitImportInfoStatus(pageData);
    }

    @Override
    public void returnCerSysteminitImportInfoStatus(PageData pageData) {
        // 标记删除
        pageData.put("deleted", 0);
        // 标记数据无错 isHaveError：0无错，1有错，5退回
        pageData.put("isHaveError", 5);
        // 没有超时上报
        pageData.put("is_uplpad_timeout", 0);
        // 是否上报正式库
        pageData.put("is_uploaded", 0);

        cerSysteminitImportInfoMapper.returnCerSysteminitImportInfoStatus(pageData);
    }

    @Override
    public List<LinkedHashMap<String, Object>> queryAllExportDataBy(PageData pageData) {

        String userId = (String) pageData.get("user");
        String ids = (String) pageData.get("ids");

        // 获取extFlag
        String extFlag = sysUserService.findUserExtFlag(userId);

        // 查询数据自定并分组
        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
        Map<String, List<SysDict>> keyListMap = allCerDicts
            .stream()
            .collect(Collectors.groupingBy(SysDict::getDictType));

        // 获取ids
        List<String> idList = new ArrayList<>();
        if (!StringUtils.isEmpty(userId)) {
            idList.addAll(Arrays.asList(ids.split("\\|")));
        }

        List<LinkedHashMap<String, Object>> list = cerSysteminitImportInfoMapper.selectAllByExtFlagAndIdList(
            extFlag,
            idList);

        keyListMap
            .entrySet()
            .parallelStream()
            .forEach(entry -> {
                // key
                String key = entry.getKey();
                if (key.equals("xb_code")) {
                    key = "sex";
                }
                List<SysDict> dicts = entry.getValue();
                String finalKey = key;
                list
                    .stream()
                    .forEach(map -> {
                        Object o = map.get(finalKey);
                        if (o != null) {
                            Optional<SysDict> first = dicts
                                .stream()
                                .filter(sysDict -> sysDict
                                    .getDictValue()
                                    .equals(o.toString()))
                                .findFirst();
                            first.ifPresent(sysDict -> {
                                map.put(finalKey,
                                        Optional
                                            .ofNullable(sysDict.getDictName())
                                            .orElse(""));
                            });
                        }
                    });
            });

        return list;
    }

    @Override
    public Map<String, Object> waitingFollowUpPersonnel(PageData pageData) {
        // 获取所有数据上报信息
        List<LinkedHashMap<String, Object>> mapList = (List<LinkedHashMap<String, Object>>) listAllTableData(pageData).get("list");
        if (StringUtils.isNotEmpty(mapList)) {
            // 查询随访列表中已数据上报的信息
            List<LinkedHashMap<String, Object>> followUpList = (List<LinkedHashMap<String, Object>>) followUpListService.selList(pageData).get("list");
            if (StringUtils.isNotEmpty(followUpList)) {
                mapList = mapList.stream().filter(list -> followUpList.stream().noneMatch(item -> item.get("cer_systeminit_import_info_id").equals(list.get("id")))).collect(Collectors.toList());
            }
            // 查询治疗列表中已数据上报的信息
            List<LinkedHashMap<String, Object>> cerTreatmentInfo = (List<LinkedHashMap<String, Object>>) cerTreatmentInfoService.findAllList(pageData).get("list");
            if (StringUtils.isNotEmpty(cerTreatmentInfo)) {
                mapList = mapList.stream().filter(list -> cerTreatmentInfo.stream().noneMatch(item -> item.get("systeminitId").equals(list.get("id")))).collect(Collectors.toList());
            }
        }
        return PaginationBuilder.buildResult(mapList);
    }

    @Override
    public List<LinkedHashMap<String, Object>> newQueryAllExportData(PageData pageData) {
        String userId = (String) pageData.get("user");
        Object idsData = pageData.get("ids");
        List<String> ids = new ArrayList<>();
        if (idsData != null) {
            ids = Arrays.asList(String.valueOf(idsData).split("\\|"));
        }
        // 获取extFlag
        String extFlag = sysUserService.findUserExtFlag(userId);
        List<LinkedHashMap<String, Object>> list = cerSysteminitImportInfoMapper.newQueryAllExportData(extFlag,idsData, ids, pageData);
        // 查询数据自定并分组
        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
        Map<String, List<SysDict>> keyListMap = allCerDicts
                .stream()
                .collect(Collectors.groupingBy(SysDict::getDictType));
        keyListMap.entrySet().parallelStream().forEach(entry -> {
            // key
            String key = entry.getKey();
            List<SysDict> dicts = entry.getValue();
            list.parallelStream().forEach(item->{
                Object o = item.get(key);
                if (o!=null) {
                    Optional<SysDict> first = dicts.stream()
                            .filter(sysDict -> sysDict.getDictValue().equals(o.toString())).findFirst();
                    first.ifPresent(sysDict -> {
                        item.put(key, sysDict.getDictName());
                    });
                }
            });
        });
        return list;
    }

    @Override
    public JsonObj del(String id) {
        // 判断随访列表、治疗列表存不存在
        List<ZjcodeFollowUpList> followUpList=followUpListService.getDataByInitId(id);
        List<CerTreatmentInfo> treatmentInfos=cerTreatmentInfoService.getDataByInitId(id);
        if (CollectionUtils.isNotEmpty(followUpList)||CollectionUtils.isNotEmpty(treatmentInfos)) {
            return JsonObj.error("数据已经存在随访或治疗数据，不能删除！");
        }
        // 删除初始数据
        int  count = cerSysteminitImportInfoMapper.del(id);
        if (count>0) {
            return JsonObj.success("删除成功");
        }else{
            return JsonObj.error("删除失败");
        }
    }

    @Override
    public JsonObj imageEscalation(PageData pageData) {
        List<String> returnList = new ArrayList<>();
        String userId = (String) pageData.get("user");
        String extFlag = sysUserService.findUserExtFlag(userId);
        // 查询当前机构下的上报信息
        List<LinkedHashMap<String, Object>> importInfoList = cerSysteminitImportInfoMapper.selectAllByExtFlagAndIdList(extFlag, null);
        List<String> idList = importInfoList.stream().map(item -> item.get("id").toString()).collect(Collectors.toList());

        Object data = pageData.get("data");
        if (data != null && StringUtils.isNotEmpty(idList)) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                List<LinkedHashMap<String, Object>> dataList = objectMapper.readValue(data.toString(), List.class);
                dataList.forEach(item -> {
                    String filename = item.get("originalFilename").toString();
                    String[] str = filename.split("_");
                    String[] split = str[0].split("-");
                    if (split.length == 3) {
                        switch (split[2]) {
                            case "内镜":
                            case "内镜号":
                                // 查询当前机构下是否存在此上报信息
                                List<String> ids1 = cerSysteminitImportInfoMapper.selByNameAndNjzlTime(split[0], timeFormat(split[1]), idList);
                                if (StringUtils.isEmpty(ids1)) {
                                    returnList.add(filename);
                                    break;
                                }
                                cerSysteminitImportInfoMapper.updateNjReport(item.get("filePath").toString(), item.get("fileUrl").toString(), ids1);
                                break;
                            case "病理":
                            case "病理号":
                                // 查询当前机构下是否存在此上报信息
                                List<String> ids2 = cerSysteminitImportInfoMapper.selByNameAndBlTime(split[0], timeFormat(split[1]), idList);
                                if (StringUtils.isEmpty(ids2)) {
                                    returnList.add(filename);
                                    break;
                                }
                                cerSysteminitImportInfoMapper.updateBlReport(item.get("filePath").toString(), item.get("fileUrl").toString(), ids2);
                                break;
                            default:
                                break;
                        }
                    } else {
                        returnList.add(filename);
                    }
                });
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }

        }
        if (StringUtils.isEmpty(returnList)) {
            return JsonObj.success("上报成功");
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("list", returnList);
            return JsonObj.success(map);
        }
    }


    private String generateCerDataInitFileSavePath(MultipartFile file, String userId) {
        // 生成新的文件名称
        String fileName =
                DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS") + "_" + userId + "_" + file
                        .getOriginalFilename()
                        .substring(0,
                                file
                                        .getOriginalFilename()
                                        .lastIndexOf('.')) + file
                        .getOriginalFilename()
                        .substring(file
                                .getOriginalFilename()
                                .lastIndexOf('.'));

        // 生成文件的存放路径
        // 日期目录
        String dirName = cerPersonFileInDisk + DateFormatUtils.format(new Date(), "yyyyMMdd");
        File dir = new File(dirName);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirName + "/" + fileName;
    }

    @Override
    public File commonImportConfig(MultipartFile file, String userId ){
        File tmpfile = new File(generateCerDataInitFileSavePath(file,userId));
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), tmpfile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return tmpfile;
    }

    @Override
    public void getRedisByAddressCode(List<CityEntity> allCityInfo,List<CityEntity> allAreaInfo,List<CityEntity> allStreetInfo,List<CityEntity> allVillageInfo){
        String cityKey= MConsts.URL_Address + "cityList";
        String cityJson= redisUtils.get(cityKey);
        if (StringUtils.isNotEmpty(cityJson)) {
            allCityInfo.addAll(JSONObject.parseArray(cityJson,CityEntity.class));
        }else{
            allCityInfo.addAll(sequenceMapper.getAllCityInfoByAnHui());
            redisUtils.update(cityKey,JSONObject.toJSONString(allCityInfo));
        }
        String areaKey= MConsts.URL_Address + "areaList";
        String areaJson= redisUtils.get(areaKey);
        if (StringUtils.isNotEmpty(areaJson)) {
            allAreaInfo.addAll(JSONObject.parseArray(areaJson,CityEntity.class));
        }else{
            allAreaInfo.addAll(sequenceMapper.getAllAreaInfoByAnHui());
            redisUtils.update(areaKey,JSONObject.toJSONString(allAreaInfo));
        }
        String streetKey= MConsts.URL_Address + "streetList";
        String streetJson= redisUtils.get(streetKey);
        if (StringUtils.isNotEmpty(streetJson)) {
            allStreetInfo.addAll(JSONObject.parseArray(streetJson,CityEntity.class));
        }else{
            allStreetInfo.addAll(sequenceMapper.getAllStreetInfoByAnHui());
            redisUtils.update(streetKey,JSONObject.toJSONString(allStreetInfo));
        }
        String villageKey= MConsts.URL_Address + "villageList";
        String villageJson= redisUtils.get(villageKey);
        if (StringUtils.isNotEmpty(villageJson)) {
            allVillageInfo.addAll(JSONObject.parseArray(villageJson,CityEntity.class));
        }else{
            allVillageInfo.addAll(sequenceMapper.getAllVillageInfoByAnHui());
            redisUtils.update(villageKey,JSONObject.toJSONString(allVillageInfo));
        }
    }

    @Override
    public JsonObj editPhysicalExaminationInfo(ZjcodePhysicalExaminationInfo info) {
        // 查询当前数据是否绑定体检表
        ZjcodePhysicalExaminationInfo bindInfo = physicalExaminationInfoMapper.selByInfoId(info.getInfoId());
        if (bindInfo != null) {
            // 更新
            info.setId(bindInfo.getId());
            physicalExaminationInfoMapper.updateByPrimaryKeySelective(info);
            return JsonObj.success("体检表更新成功");
        } else {
            // 新增
            info.setId(get32UUID());
            physicalExaminationInfoMapper.insertSelective(info);
            return JsonObj.success("体检表提交成功");
        }
    }

    @Override
    public JsonObj getPhysicalExaminationByInfoId(String infoId) {
        Map<String, Object> map = new HashMap<>();
        ZjcodePhysicalExaminationInfo zjcodePhysicalExaminationInfo = physicalExaminationInfoMapper.selByInfoId(infoId);
        if (zjcodePhysicalExaminationInfo != null) {
            map.put("id", zjcodePhysicalExaminationInfo.getId());
            map.put("infoId", zjcodePhysicalExaminationInfo.getInfoId());
            map.put("name", zjcodePhysicalExaminationInfo.getName());
            map.put("idCard", zjcodePhysicalExaminationInfo.getIdCard());
            map.put("screeningId", zjcodePhysicalExaminationInfo.getScreeningId());
            map.put("phone", zjcodePhysicalExaminationInfo.getPhone());
            map.put("content", zjcodePhysicalExaminationInfo.getContent());
        }
        return JsonObj.success(map);
    }

    @Override
    public JsonObj getAreaByUserId(Long userId) {
        String orgId = sysUserService.findOrgByUserId(String.valueOf(userId));
        TkmSysOrg sysOrg = orgMapper.selectByPrimaryKey(Long.valueOf(orgId));
        Map<String, Object> map = sequenceMapper.selByProvinceNameAndCityName(sysOrg.getProvinceName(), sysOrg.getCityName());
        return JsonObj.success(map);
    }



    @Override
    public void exportSelfTestTable(PageData pageData,HttpServletResponse response) {
        String userId = (String) pageData.get("user");
        Object idsData = pageData.get("ids");
        List<String> ids = new ArrayList<>();
        if (idsData != null) {
            ids = Arrays.asList(String.valueOf(idsData).split("\\|"));
        }
        // 获取extFlag
        String extFlag = sysUserService.findUserExtFlag(userId);
        pageData.put("idsData", idsData);
        pageData.put("ids", ids);
        pageData.put("extFlag", extFlag);
        pageData.put("currentPage","1");
        pageData.put("pageSize","999999999");
        // 读取区域信息
        pageData = Utils.transitionRegionInfo(pageData);
        MPage mPage = getPageInfo(pageData);
        Page<Object> page = PageHelper.startPage(mPage.getCurrentPage(), mPage.getPageSize());
        List<LinkedHashMap<String, Object>> mapList = cerSysteminitImportInfoMapper.listAllTableData(pageData);

        if (CollectionUtils.isEmpty(mapList)) {
            throw new RuntimeException("查询列表为空");
        }
        List<Object> contentValues = mapList.stream()
                .filter(map -> map.get("risk_report_id") != null)
                .map(map -> map.get("risk_report_id"))
                .collect(Collectors.toList());
        // 查自测表集合信息
        List<ZjcodeSelfTestInfo> selfTestList = zjcodeSelfTestInfoService.getTestContentByIds(contentValues);
        Map<Long,TkmSysOrg> orgInfoMap = tkmSysOrgService.getOrgInfoMap();
        List<SelfTestTableVo> resultList=new ArrayList<>();
//        mapList.forEach(item->{
//            todo:因业务需求：导出自测表已经填写的，即content不为null
//            info.setProvinceName(ObjectUtils.isNotEmpty(item.get("province_name"))?item.get("province_name").toString():"");
//            info.setCityName(ObjectUtils.isNotEmpty(item.get("city_name"))?item.get("city_name").toString():"");
//            info.setDiseasName(ObjectUtils.isNotEmpty(item.get("district_name"))?item.get("district_name").toString():"");
//            info.setAddress(ObjectUtils.isNotEmpty(item.get("addr"))?item.get("addr").toString():"");
//            info.setUserName(ObjectUtils.isNotEmpty(item.get("name"))?item.get("name").toString():"");
//            info.setSex(ObjectUtils.isNotEmpty(item.get("sex"))?item.get("sex").toString():"");
//            info.setIdCard(ObjectUtils.isNotEmpty(item.get("sfz"))?item.get("sfz").toString():"");
//            info.setPhone(ObjectUtils.isNotEmpty(item.get("phone"))?item.get("phone").toString():"");
            selfTestList.forEach(each->{
                SelfTestTableVo info =new SelfTestTableVo();
                TkmSysOrg org = orgInfoMap.get(each.getOrgId());
//                if (Objects.equals(item.get("risk_report_id"),each.getId())) {
                    // 是否是高危人群（0不是 1是 ）
                    String highRisk = each.getHighRisk() == 1? "是" : "不是";
                    info.setHighRisk(highRisk);
                    info.setHighRiskRemark(ObjectUtils.isNotEmpty(each.getHighRiskRemark())?each.getHighRiskRemark():"");

                    String content = each.getContent();
                    String colorectalCancerContent = each.getColorectalCancerContent();
                    if (ObjectUtils.isNotEmpty(content)) {
                        Gson gson = new Gson();
                        JsonObject jsonObject = gson.fromJson(content, JsonObject.class);
                        setContentSelfTestInfo(jsonObject,info,colorectalCancerContent,org);
                        resultList.add(info);
                    }
//                }
            });
//        });
//        exportExcelUtil(resultList,response);
        try {
            ExcelUtil.setExcelResponseProp(response, "数据上报-自测表导出");
            EasyExcel.write(response.getOutputStream())
                    .head(SelfTestTableVo.class)
                    .autoCloseStream(Boolean.FALSE)
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet("自测表")
                    .doWrite(resultList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用ExcelUtils类下的exportExcel方法导出
     * @param resultList
     * @param response
     */
    public void exportExcelUtil(List<SelfTestTableVo> resultList,HttpServletResponse response){
        List<LinkedHashMap<String, Object>> dataList = new ArrayList<>();
        resultList.forEach(item->{
            LinkedHashMap<String, Object> map =new LinkedHashMap<>();
            map.put("provinceName",item.getProvinceName());
            map.put("cityName",item.getCityName());
            map.put("districtName",item.getDiseasName());
            map.put("address",item.getAddress());
            map.put("userName",item.getUserName());
            map.put("sex",item.getSex());
            map.put("idCard", item.getIdCard());
            map.put("phone", item.getPhone());
            map.put("maritalStatus", item.getMaritalStatus());
            map.put("degreeEducation", item.getDegreeEducation());
            map.put("population", item.getPopulation());
            map.put("income", item.getIncome());
            map.put("height", item.getHeight());
            map.put("weight", item.getWeight());
            map.put("systolicPressure", item.getSystolicPressure());
            map.put("diastolicPressure", item.getDiastolicPressure());
            map.put("headwaters", item.getHeadwaters());
            map.put("smoke", item.getSmoke());
            map.put("smokingFrequency", item.getSmokingFrequency());
            map.put("smokingYear", item.getSmokingYear());
            map.put("drink", item.getDrink());
            map.put("drinkQuantity", item.getDrinkQuantity());
            map.put("drinkFrequency", item.getDrinkFrequency());
            map.put("blackTea", item.getBlackTea());
            map.put("blackTeaYear", item.getBlackTeaYear());
            map.put("greenTea", item.getGreenTea());
            map.put("greenTeaYear", item.getGreenTeaYear());
            map.put("vegetable", item.getVegetable());
            map.put("fruits", item.getFruits());
            map.put("eggsMilk", item.getEggsMilk());
            map.put("beanFood", item.getBeanFood());
            map.put("sunDryFood", item.getSunDryFood());
            map.put("deepFryFood", item.getDeepFryFood());
            map.put("hotFood", item.getHotFood());
            map.put("mildewFood", item.getMildewFood());
            map.put("mealTime", item.getMealTime());
            map.put("tooth", item.getTooth());
            map.put("loseTooth", item.getLoseTooth());
            map.put("plantTooth", item.getPlantTooth());
            map.put("gastroscope", item.getGastroscope());
            map.put("oesophagitis", item.getOesophagitis());
            map.put("oesophagitisTime", item.getOesophagitisTime());
            map.put("cardiaIntestinalMetaplasia", item.getCardiaIntestinalMetaplasia());
            map.put("cardiaIntestinalMetaplasiaTime", item.getCardiaIntestinalMetaplasiaTime());
            map.put("nonAtrophicGastritis", item.getNonAtrophicGastritis());
            map.put("nonAtrophicGastritisTime", item.getNonAtrophicGastritisTime());
            map.put("atrophicGastritis", item.getAtrophicGastritis());
            map.put("atrophicGastritisTime", item.getAtrophicGastritisTime());
            map.put("intestinalMetaplasia", item.getIntestinalMetaplasia());
            map.put("intestinalMetaplasiaTime", item.getIntestinalMetaplasiaTime());
            map.put("gastricAndDuodenalUlcers", item.getGastricAndDuodenalUlcers());
            map.put("gastricAndDuodenalUlcersTime", item.getGastricAndDuodenalUlcersTime());
            map.put("gastricPolyps", item.getGastricPolyps());
            map.put("gastricPolypsTime", item.getGastricPolypsTime());
            map.put("lowGradeIntraepithelialNeoplasia", item.getLowGradeIntraepithelialNeoplasia());
            map.put("lowGradeIntraepithelialNeoplasiaTime", item.getLowGradeIntraepithelialNeoplasiaTime());
            map.put("highGradeNeoplasiaAndEarlyCancer", item.getHighGradeNeoplasiaAndEarlyCancer());
            map.put("highGradeNeoplasiaAndEarlyCancerTime", item.getHighGradeNeoplasiaAndEarlyCancerTime());
            map.put("barrettEsophagus", item.getBarrettEsophagus());
            map.put("barrettEsophagusTime", item.getBarrettEsophagusTime());
            map.put("historyOfBenignDiseaseSubtotalGastrectomy", item.getHistoryOfBenignDiseaseSubtotalGastrectomy());
            map.put("historyOfBenignDiseaseSubtotalGastrectomyTime", item.getHistoryOfBenignDiseaseSubtotalGastrectomyTime());
            map.put("historyOfSubtotalGastrectomyForGastricCancer", item.getHistoryOfSubtotalGastrectomyForGastricCancer());
            map.put("historyOfSubtotalGastrectomyForGastricCancerTime", item.getHistoryOfSubtotalGastrectomyForGastricCancerTime());
            map.put("gastricMucosaGiantFoldSign", item.getGastricMucosaGiantFoldSign());
            map.put("gastricMucosaGiantFoldSignTime", item.getGastricMucosaGiantFoldSignTime());
            map.put("helicobacterPyloriInfection", item.getHelicobacterPyloriInfection());
            map.put("helicobacterPyloriInfectionTime", item.getHelicobacterPyloriInfectionTime());
            map.put("helicobacterPyloriDetectionMethod", item.getHelicobacterPyloriDetectionMethod());
            map.put("hepatitis", item.getHepatitis());
            map.put("hepatitisTime", item.getHepatitisTime());
            map.put("squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTract", item.getSquamousCellCarcinomaOfTheHeadNeckOrRespiratoryTract());
            map.put("squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractTime", item.getSquamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractTime());
            map.put("perniciousAnemia", item.getPerniciousAnemia());
            map.put("perniciousAnemiaTime", item.getPerniciousAnemiaTime());
            map.put("elseStr", item.getElseStr());
            map.put("diseasName", item.getDiseasName());
            map.put("elseTime", item.getElseTime());
            map.put("firstDegreeRelativeHadTumor", item.getFirstDegreeRelativeHadTumor());
            map.put("domesticRelationHadTumor", item.getDomesticRelationHadTumor());
            dataList.add(map);
        });

                // 组装表头
        List<String> headList = Arrays.asList(
                "省份",
                "城市",
                "区县",
                "详细地址",
                "姓名",
                "性别",
                "身份证",
                "电话",
                "婚姻状况",
                "教育程度",
                "您家现在有几口人?（同户籍）",
                "您家庭平均年收入大约多少元",
                "身高(cm)",
                "体重(Kg)",
                "收缩压",
                "舒张压",
                "饮水主要来源",
                "吸烟",
                "吸烟频率(支/天)",
                "吸烟持续年数(年)",
                "饮酒",
                "饮酒量",
                "饮酒频率(年)",
                "饮红茶",
                "饮茶持续年数",
                "饮绿茶",
                "饮茶持续年数",
                "新鲜蔬菜",
                "新鲜水果",
                "肉蛋奶类",
                "豆类食品",
                "腌晒食品",
                "油炸食品",
                "热烫食品",
                "霉变食品",
                "您平时吃一顿饭的时间是多少分钟？",
                "有没有牙齿缺失",
                "缺失几颗牙",
                "种植/镶几颗牙",
                "是否做过胃镜",
                "反流性食管炎",
                "疾病确诊后时间",
                "贲门肠上皮化生",
                "疾病确诊后时间",
                "非萎缩性胃炎",
                "疾病确诊后时间",
                "萎缩性胃炎",
                "疾病确诊后时间",
                "肠上皮化生",
                "疾病确诊后时间",
                "胃、十二指肠溃疡",
                "疾病确诊后时间",
                "胃息肉",
                "疾病确诊后时间",
                "低级别上皮内瘤变",
                "疾病确诊后时间",
                "高级别瘤变与早癌",
                "疾病确诊后时间",
                "Barrett食管（巴雷特食管）",
                "疾病确诊后时间",
                "良性疾病胃大部切除史",
                "疾病确诊后时间",
                "胃癌胃大部切除史",
                "疾病确诊后时间",
                "胃黏膜巨大皱褶征",
                "疾病确诊后时间",
                "幽门螺杆菌感染",
                "疾病确诊后时间",
                "幽门螺杆菌检测方法",
                "肝炎",
                "疾病确诊后时间",
                "头颈部或呼吸道鳞癌",
                "疾病确诊后时间",
                "恶性贫血",
                "疾病确诊后时间",
                "其它",
                "疾病名称",
                "疾病确诊后时间",
                "你家中有没有人得过肿瘤",
                "得过肿瘤：亲属关系-肿瘤情况"
        );


        try {
            // 导出
            ExcelUtils.exportExcel(headList, dataList, "数据上报-自测表导出", response);
        } catch (Exception e) {
        }
    }


    /**
     * 自测表信息转换成字段对应的文字，导出数据
     * @param jsonObject
     * @param info
     */
    @Override
    public void setContentSelfTestInfo(JsonObject jsonObject, SelfTestTableVo info,Object colorectalCancerContent,TkmSysOrg org) {
        // 【基本信息】
        // 省份
        info.setProvinceName(org.getProvinceName());
//        info.setProvinceName(ObjectUtils.isNotEmpty(jsonObject.get("provinceName"))?jsonObject.get("provinceName").toString().replaceAll("\"", "")
//                :ObjectUtils.isNotEmpty(info.getProvinceName())?info.getProvinceName():"");
        // 城市
        info.setCityName(org.getCityName());
//        info.setCityName(ObjectUtils.isNotEmpty(jsonObject.get("cityName"))?jsonObject.get("cityName").toString().replaceAll("\"", "")
//                :ObjectUtils.isNotEmpty(info.getCityName())?info.getCityName():"");
        // 区县
        info.setDistrictName(org.getRegionName());
//        info.setDistrictName(ObjectUtils.isNotEmpty(jsonObject.get("districtName"))?jsonObject.get("districtName").toString().replaceAll("\"", "")
//                :ObjectUtils.isNotEmpty(info.getDistrictName())?info.getDistrictName():"");
        // 详细地址
        info.setAddress(ObjectUtils.isNotEmpty(jsonObject.get("address"))?jsonObject.get("address").toString().replaceAll("\"", "")
                :ObjectUtils.isNotEmpty(info.getAddress())?info.getAddress():"");
        // 姓名
        info.setUserName(ObjectUtils.isNotEmpty(jsonObject.get("userName"))?jsonObject.get("userName").toString().replaceAll("\"", "")
                :ObjectUtils.isNotEmpty(info.getUserName())?info.getUserName():"");
        // 性别
        String sexMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("sex"))) {
            String sex = jsonObject.get("sex").toString().replaceAll("\"", "");
            switch (sex) {
                case "1":
                    sexMap = "男";
                    break;
                case "2":
                    sexMap = "女";
                    break;
                default:
                    // 处理其他未知情况
                    sexMap=ObjectUtils.isNotEmpty(info.getSex())?info.getSex():"";
                    break;
            }
        }
        info.setSex(sexMap);
        // 身份证
        info.setIdCard(ObjectUtils.isNotEmpty(jsonObject.get("idCard"))?jsonObject.get("idCard").toString().replaceAll("\"", "")
                :ObjectUtils.isNotEmpty(info.getIdCard())?info.getIdCard():"");
        // 电话
        info.setPhone(ObjectUtils.isNotEmpty(jsonObject.get("phone"))?jsonObject.get("phone").toString().replaceAll("\"", "")
                :ObjectUtils.isNotEmpty(info.getPhone())?info.getPhone():"");
        // "maritalStatus": "1",  婚姻状况
        String maritalStatusMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("maritalStatus"))) {
            // 1未婚 2已婚 3离异 4丧偶
            String maritalStatus = jsonObject.get("maritalStatus").toString().replaceAll("\"", "");
            maritalStatusMap = getMaritalStatusMap(maritalStatus, maritalStatusMap);
        }
        info.setMaritalStatus(maritalStatusMap);
        // "degreeEducation": "2",  教育程度
        String degreeEducationMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("degreeEducation"))) {
            String degreeEducation = jsonObject.get("degreeEducation").toString().replaceAll("\"", "");
            degreeEducationMap = getDegreeEducationMap(degreeEducation, degreeEducationMap);
        }
        info.setDegreeEducation(degreeEducationMap);
        // "population": "3",  您家现在有几口人?（同户籍）
        String populationMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("population"))) {
            String population = jsonObject.get("population").toString().replaceAll("\"", "");
            populationMap = getPopulationMap(population, populationMap);
        }
        info.setPopulation(populationMap);
        //  "income": "4",  您家庭平均年收入大约多少元
        String incomeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("income"))) {
            String income = jsonObject.get("income").toString().replaceAll("\"", "");
            incomeMap = getIncomeMap(income, incomeMap);
        }
        info.setIncome(incomeMap);
        //  "height": "111",  身高(cm)
        info.setHeight(ObjectUtils.isNotEmpty(jsonObject.get("height"))?jsonObject.get("height").toString().replaceAll("\"", ""):"");
        //  "weight": "43",   体重(Kg)
        info.setWeight(ObjectUtils.isNotEmpty(jsonObject.get("weight"))?jsonObject.get("weight").toString().replaceAll("\"", ""):"");
        //  "systolicPressure": "2",  收缩压
        String systolicPressureMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("systolicPressure"))) {
            String systolicPressure = jsonObject.get("systolicPressure").toString().replaceAll("\"", "");
            systolicPressureMap = getSystolicPressureMap(systolicPressure, systolicPressureMap);
        }
        info.setSystolicPressure(systolicPressureMap);
        //  "diastolicPressure": "2", 舒张压
        String diastolicPressureMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("diastolicPressure"))) {
            String diastolicPressure = jsonObject.get("diastolicPressure").toString().replaceAll("\"", "");
            diastolicPressureMap = getDiastolicPressureMap(diastolicPressure, diastolicPressureMap);
        }
        info.setDiastolicPressure(diastolicPressureMap);
        //  【生活方式】
        //   "headwaters": "2",  饮水主要来源
        String headwatersMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("headwaters"))) {
            String headwaters = jsonObject.get("headwaters").toString().replaceAll("\"", "");
            headwatersMap = getHeadwatersMap(headwaters, headwatersMap);
        }
        info.setHeadwaters(headwatersMap);
        //   "smoke": "2",  吸烟
        String smokeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("smoke"))) {
            String smoke = jsonObject.get("smoke").toString().replaceAll("\"", "");
            smokeMap = Objects.equals("1", smoke) ? "是" : Objects.equals("2", smoke) ? "否" : "";
        }
        info.setSmoke(smokeMap);
        //  "smokingFrequency": "1", 吸烟频率(支/天)
        info.setSmokingFrequency(ObjectUtils.isNotEmpty(jsonObject.get("smokingFrequency"))?jsonObject.get("smokingFrequency").toString().replaceAll("\"", ""):"");
        //   "smokingYear": "1", 吸烟持续年数(年)
        info.setSmokingYear(ObjectUtils.isNotEmpty(jsonObject.get("smokingYear"))?jsonObject.get("smokingYear").toString().replaceAll("\"", ""):"");
        //   "drink": "3",   饮酒
        String drinkMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("drink"))) {
            String drink = jsonObject.get("drink").toString().replaceAll("\"", "");
            drinkMap = getDrinkString(drink, drinkMap);
        }
        info.setDrink(drinkMap);
        //  "drinkQuantity":"",饮酒量
        String drinkQuantityMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("drinkQuantity"))) {
            String drinkQuantity = jsonObject.get("drinkQuantity").toString().replaceAll("\"", "");
            drinkQuantityMap = getDrinkQuantityMap(drinkQuantity, drinkQuantityMap);
        }
        info.setDrinkQuantity(drinkQuantityMap);
        //   "drinkFrequency":"",饮酒频率(年)
        String drinkFrequencyMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("drinkFrequency"))) {
            String drinkFrequency = jsonObject.get("drinkFrequency").toString().replaceAll("\"", "");
            drinkFrequencyMap = getDrinkFrequencyMap(drinkFrequency, drinkFrequencyMap);
        }
        info.setDrinkFrequency(drinkFrequencyMap);
        //   "blackTea": "3",饮红茶
        String blackTeaMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("blackTea"))) {
            String blackTea = jsonObject.get("blackTea").toString().replaceAll("\"", "");
            blackTeaMap = getDrinkString(blackTea, blackTeaMap);
        }
        info.setBlackTea(blackTeaMap);
        //  "blackTeaYear":"1",饮茶持续年数
        String blackTeaYearMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("blackTeaYear"))) {
            blackTeaYearMap = getDurationMap(jsonObject.get("blackTeaYear").toString().replaceAll("\"", ""));
        }
        info.setBlackTeaYear(blackTeaYearMap);
        //   "greenTea": "3",饮绿茶
        String greenTeaMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("greenTea"))) {
            String greenTea = jsonObject.get("greenTea").toString().replaceAll("\"", "");
            greenTeaMap = getDrinkString(greenTea, greenTeaMap);
        }
        info.setGreenTea(greenTeaMap);
        //   "greenTeaYear": "2",饮茶持续年数
        String greenTeaYearMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("greenTeaYear"))) {
            greenTeaYearMap = getDurationMap(jsonObject.get("greenTeaYear").toString().replaceAll("\"", ""));
        }
        info.setGreenTeaYear(greenTeaYearMap);
        //【下列食物您经常吃吗】
        //   "vegetable": "3", 新鲜蔬菜
        String vegetableMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("vegetable"))) {
            vegetableMap = getFoodWhetherMap(jsonObject.get("vegetable").toString().replaceAll("\"", ""));
        }
        info.setVegetable(vegetableMap);
        //  "fruits": "2",   新鲜水果
        String fruitsMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("fruits"))) {
            fruitsMap = getFoodWhetherMap(jsonObject.get("fruits").toString().replaceAll("\"", ""));
        }
        info.setFruits(fruitsMap);
        //   "eggsMilk": "3",肉蛋奶类
        String eggsMilkMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("eggsMilk"))) {
            eggsMilkMap = getFoodWhetherMap(jsonObject.get("eggsMilk").toString().replaceAll("\"", ""));
        }
        info.setEggsMilk(eggsMilkMap);
        //   "BeanFood": "2",豆类食品
        String BeanFoodMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("BeanFood"))) {
            BeanFoodMap = getFoodWhetherMap(jsonObject.get("BeanFood").toString().replaceAll("\"", ""));
        }
        info.setBeanFood(BeanFoodMap);
        //  "sunDryFood": "2",腌晒食品
        String sunDryFoodMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("sunDryFood"))) {
            sunDryFoodMap = getFoodWhetherMap(jsonObject.get("sunDryFood").toString().replaceAll("\"", ""));
        }
        info.setSunDryFood(sunDryFoodMap);
        //   "deepFryFood": "2",油炸食品
        String deepFryFoodMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("deepFryFood"))) {
            deepFryFoodMap = getFoodWhetherMap(jsonObject.get("deepFryFood").toString().replaceAll("\"", ""));
        }
        info.setDeepFryFood(deepFryFoodMap);
        //  "hotFood": "2",热烫食品
        String hotFoodMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("hotFood"))) {
            hotFoodMap = getFoodWhetherMap(jsonObject.get("hotFood").toString().replaceAll("\"", ""));
        }
        info.setHotFood(hotFoodMap);
        //   "mildewFood": "2",霉变食品
        String mildewFoodMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("mildewFood"))) {
            mildewFoodMap = getFoodWhetherMap(jsonObject.get("mildewFood").toString().replaceAll("\"", ""));
        }
        info.setMildewFood(mildewFoodMap);
        //   "mealTime": "3",  您平时吃一顿饭的时间是多少分钟？
        String mealTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("mealTime"))) {
            String mealTime = jsonObject.get("mealTime").toString().replaceAll("\"", "");
            mealTimeMap = getMealTimeMap(mealTime, mealTimeMap);
        }
        info.setMealTime(mealTimeMap);
        //   "tooth": "2", 有没有牙齿缺失
        String toothMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("tooth"))) {
            toothMap = getWhetherMap(jsonObject.get("tooth").toString().replaceAll("\"", ""));
        }
        info.setTooth(toothMap);
        //  "loseTooth": "1",缺失几颗牙
        String loseToothMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("loseTooth"))) {
            String loseTooth = jsonObject.get("loseTooth").toString().replaceAll("\"", "");
            loseToothMap = getLoseToothMap(loseTooth, loseToothMap);
        }
        info.setLoseTooth(loseToothMap);
        //   "plantTooth": "1",  种植/镶几颗牙
        String plantToothMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("plantTooth"))) {
            String plantTooth = jsonObject.get("plantTooth").toString().replaceAll("\"", "");
            plantToothMap = getPlantToothMap(plantTooth, plantToothMap);
        }
        info.setPlantTooth(plantToothMap);
        //【消化系统疾病史】
        //   "gastroscope": "2",是否做过胃镜
        String gastroscopeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("gastroscope"))) {
            gastroscopeMap = getWhetherMap(jsonObject.get("gastroscope").toString().replaceAll("\"", ""));
        }
        info.setGastroscope(gastroscopeMap);
        //   "oesophagitis": "2",反流性食管炎
        String oesophagitisMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("oesophagitis"))) {
            oesophagitisMap = getWhetherMap(jsonObject.get("oesophagitis").toString().replaceAll("\"", ""));
        }
        info.setOesophagitis(oesophagitisMap);
        //   "oesophagitisTime": "1",疾病确诊后时间
        String oesophagitisTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("oesophagitisTime"))) {
            oesophagitisTimeMap = getDurationMap(jsonObject.get("oesophagitisTime").toString().replaceAll("\"", ""));
        }
        info.setOesophagitisTime(oesophagitisTimeMap);
        //   "cardiaIntestinalMetaplasia": "2",  贲门肠上皮化生
        String cardiaIntestinalMetaplasiaMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("cardiaIntestinalMetaplasia"))) {
            cardiaIntestinalMetaplasiaMap = getWhetherMap(jsonObject.get("cardiaIntestinalMetaplasia").toString().replaceAll("\"", ""));
        }
        info.setCardiaIntestinalMetaplasia(cardiaIntestinalMetaplasiaMap);
        //  "cardiaIntestinalMetaplasiaTime":"2",疾病确诊后时间
        String cardiaIntestinalMetaplasiaTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("cardiaIntestinalMetaplasiaTime"))) {
            cardiaIntestinalMetaplasiaTimeMap = getDurationMap(jsonObject.get("cardiaIntestinalMetaplasiaTime").toString().replaceAll("\"", ""));
        }
        info.setCardiaIntestinalMetaplasiaTime(cardiaIntestinalMetaplasiaTimeMap);
        //  "nonAtrophicGastritis": "2",非萎缩性胃炎
        String nonAtrophicGastritisMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("nonAtrophicGastritis"))) {
            nonAtrophicGastritisMap = getWhetherMap(jsonObject.get("nonAtrophicGastritis").toString().replaceAll("\"", ""));
        }
        info.setNonAtrophicGastritis(nonAtrophicGastritisMap);
        //  "nonAtrophicGastritisTime": "2",疾病确诊后时间
        String nonAtrophicGastritisTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("nonAtrophicGastritisTime"))) {
            nonAtrophicGastritisTimeMap = getDurationMap(jsonObject.get("nonAtrophicGastritisTime").toString().replaceAll("\"", ""));
        }
        info.setNonAtrophicGastritisTime(nonAtrophicGastritisTimeMap);
        //   "atrophicGastritis": "2",萎缩性胃炎
        String atrophicGastritisMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("atrophicGastritis"))) {
            atrophicGastritisMap = getWhetherMap(jsonObject.get("atrophicGastritis").toString().replaceAll("\"", ""));
        }
        info.setAtrophicGastritis(atrophicGastritisMap);
        //   "atrophicGastritisTime": "1",疾病确诊后时间
        String atrophicGastritisTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("atrophicGastritisTime"))) {
            atrophicGastritisTimeMap = getDurationMap(jsonObject.get("atrophicGastritisTime").toString().replaceAll("\"", ""));
        }
        info.setAtrophicGastritisTime(atrophicGastritisTimeMap);
        //   "intestinalMetaplasia": "2", 肠上皮化生
        String intestinalMetaplasiaMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("intestinalMetaplasia"))) {
            intestinalMetaplasiaMap = getWhetherMap(jsonObject.get("intestinalMetaplasia").toString().replaceAll("\"", ""));
        }
        info.setIntestinalMetaplasia(intestinalMetaplasiaMap);
        //  "intestinalMetaplasiaTime": "1", 疾病确诊后时间
        String intestinalMetaplasiaTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("intestinalMetaplasiaTime"))) {
            intestinalMetaplasiaTimeMap = getDurationMap(jsonObject.get("intestinalMetaplasiaTime").toString().replaceAll("\"", ""));
        }
        info.setIntestinalMetaplasiaTime(intestinalMetaplasiaTimeMap);
        //   "gastricAndDuodenalUlcers": "2", 胃、十二指肠溃疡
        String gastricAndDuodenalUlcersMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("gastricAndDuodenalUlcers"))) {
            gastricAndDuodenalUlcersMap = getWhetherMap(jsonObject.get("gastricAndDuodenalUlcers").toString().replaceAll("\"", ""));
        }
        info.setGastricAndDuodenalUlcers(gastricAndDuodenalUlcersMap);
        //   "gastricAndDuodenalUlcersTime": "2", 疾病确诊后时间
        String gastricAndDuodenalUlcersTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("gastricAndDuodenalUlcersTime"))) {
            gastricAndDuodenalUlcersTimeMap = getDurationMap(jsonObject.get("gastricAndDuodenalUlcersTime").toString().replaceAll("\"", ""));
        }
        info.setGastricAndDuodenalUlcersTime(gastricAndDuodenalUlcersTimeMap);
        //  "gastricPolyps": "1",胃息肉
        String gastricPolypsMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("gastricPolyps"))) {
            gastricPolypsMap = getWhetherMap(jsonObject.get("gastricPolyps").toString().replaceAll("\"", ""));
        }
        info.setGastricPolyps(gastricPolypsMap);
        //   "gastricPolypsTime": "1",疾病确诊后时间
        String gastricPolypsTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("gastricPolypsTime"))) {
            gastricPolypsTimeMap = getDurationMap(jsonObject.get("gastricPolypsTime").toString().replaceAll("\"", ""));
        }
        info.setGastricPolypsTime(gastricPolypsTimeMap);
        //  "lowGradeIntraepithelialNeoplasia": "2", 低级别上皮内瘤变
        String lowGradeIntraepithelialNeoplasiaMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("lowGradeIntraepithelialNeoplasia"))) {
            lowGradeIntraepithelialNeoplasiaMap = getWhetherMap(jsonObject.get("lowGradeIntraepithelialNeoplasia").toString().replaceAll("\"", ""));
        }
        info.setLowGradeIntraepithelialNeoplasia(lowGradeIntraepithelialNeoplasiaMap);
        //   "lowGradeIntraepithelialNeoplasiaTime": "1",疾病确诊后时间
        String lowGradeIntraepithelialNeoplasiaTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("lowGradeIntraepithelialNeoplasiaTime"))) {
            lowGradeIntraepithelialNeoplasiaTimeMap = getDurationMap(jsonObject.get("lowGradeIntraepithelialNeoplasiaTime").toString().replaceAll("\"", ""));
        }
        info.setLowGradeIntraepithelialNeoplasiaTime(lowGradeIntraepithelialNeoplasiaTimeMap);
        //  "highGradeNeoplasiaAndEarlyCancer": "2", 高级别瘤变与早癌
        String highGradeNeoplasiaAndEarlyCancerMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("highGradeNeoplasiaAndEarlyCancer"))) {
            highGradeNeoplasiaAndEarlyCancerMap = getWhetherMap(jsonObject.get("highGradeNeoplasiaAndEarlyCancer").toString().replaceAll("\"", ""));
        }
        info.setHighGradeNeoplasiaAndEarlyCancer(highGradeNeoplasiaAndEarlyCancerMap);
        //  "highGradeNeoplasiaAndEarlyCancerTime": "2", 疾病确诊后时间
        String highGradeNeoplasiaAndEarlyCancerTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("highGradeNeoplasiaAndEarlyCancerTime"))) {
            highGradeNeoplasiaAndEarlyCancerTimeMap = getDurationMap(jsonObject.get("highGradeNeoplasiaAndEarlyCancerTime").toString().replaceAll("\"", ""));
        }
        info.setHighGradeNeoplasiaAndEarlyCancerTime(highGradeNeoplasiaAndEarlyCancerTimeMap);
        //  "barrettEsophagus": "2",  Barrett食管（巴雷特食管）
        String barrettEsophagusMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("barrettEsophagus"))) {
            barrettEsophagusMap = getWhetherMap(jsonObject.get("barrettEsophagus").toString().replaceAll("\"", ""));
        }
        info.setBarrettEsophagus(barrettEsophagusMap);
        //  "barrettEsophagusTime": "2",  疾病确诊后时间
        String barrettEsophagusTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("barrettEsophagusTime"))) {
            barrettEsophagusTimeMap = getDurationMap(jsonObject.get("barrettEsophagusTime").toString().replaceAll("\"", ""));
        }
        info.setBarrettEsophagusTime(barrettEsophagusTimeMap);
        // "historyOfBenignDiseaseSubtotalGastrectomy": "2",良性疾病胃大部切除史
        String historyOfBenignDiseaseSubtotalGastrectomyMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("historyOfBenignDiseaseSubtotalGastrectomy"))) {
            historyOfBenignDiseaseSubtotalGastrectomyMap = getWhetherMap(jsonObject.get("historyOfBenignDiseaseSubtotalGastrectomy").toString().replaceAll("\"", ""));
        }
        info.setHistoryOfBenignDiseaseSubtotalGastrectomy(historyOfBenignDiseaseSubtotalGastrectomyMap);
        //  "historyOfBenignDiseaseSubtotalGastrectomyTime": "2",疾病确诊后时间
        String historyOfBenignDiseaseSubtotalGastrectomyTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("historyOfBenignDiseaseSubtotalGastrectomyTime"))) {
            historyOfBenignDiseaseSubtotalGastrectomyTimeMap = getDurationMap(jsonObject.get("historyOfBenignDiseaseSubtotalGastrectomyTime").toString().replaceAll("\"", ""));
        }
        info.setHistoryOfBenignDiseaseSubtotalGastrectomyTime(historyOfBenignDiseaseSubtotalGastrectomyTimeMap);
        //  "historyOfSubtotalGastrectomyForGastricCancer": "2",胃癌胃大部切除史
        String historyOfSubtotalGastrectomyForGastricCancerMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("historyOfSubtotalGastrectomyForGastricCancer"))) {
            historyOfSubtotalGastrectomyForGastricCancerMap = getWhetherMap(jsonObject.get("historyOfSubtotalGastrectomyForGastricCancer").toString().replaceAll("\"", ""));
        }
        info.setHistoryOfSubtotalGastrectomyForGastricCancer(historyOfSubtotalGastrectomyForGastricCancerMap);
        //  "historyOfSubtotalGastrectomyForGastricCancerTime": "2",疾病确诊后时间
        String historyOfSubtotalGastrectomyForGastricCancerTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("historyOfSubtotalGastrectomyForGastricCancerTime"))) {
            historyOfSubtotalGastrectomyForGastricCancerTimeMap = getDurationMap(jsonObject.get("historyOfSubtotalGastrectomyForGastricCancerTime").toString().replaceAll("\"", ""));
        }
        info.setHistoryOfSubtotalGastrectomyForGastricCancerTime(historyOfSubtotalGastrectomyForGastricCancerTimeMap);
        //   "gastricMucosaGiantFoldSign": "2",胃黏膜巨大皱褶征
        String gastricMucosaGiantFoldSignMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("gastricMucosaGiantFoldSign"))) {
            gastricMucosaGiantFoldSignMap = getWhetherMap(jsonObject.get("gastricMucosaGiantFoldSign").toString().replaceAll("\"", ""));
        }
        info.setGastricMucosaGiantFoldSign(gastricMucosaGiantFoldSignMap);
        //   "gastricMucosaGiantFoldSignTime": "2",疾病确诊后时间
        String gastricMucosaGiantFoldSignTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("gastricMucosaGiantFoldSignTime"))) {
            gastricMucosaGiantFoldSignTimeMap = getDurationMap(jsonObject.get("gastricMucosaGiantFoldSignTime").toString().replaceAll("\"", ""));
        }
        info.setGastricMucosaGiantFoldSignTime(gastricMucosaGiantFoldSignTimeMap);
        //   "helicobacterPyloriInfection": "2",幽门螺杆菌感染
        String helicobacterPyloriInfectionMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("helicobacterPyloriInfection"))) {
            helicobacterPyloriInfectionMap = getWhetherMap(jsonObject.get("helicobacterPyloriInfection").toString().replaceAll("\"", ""));
        }
        info.setHelicobacterPyloriInfection(helicobacterPyloriInfectionMap);
        //   "helicobacterPyloriInfectionTime": "2",疾病确诊后时间
        String helicobacterPyloriInfectionTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("helicobacterPyloriInfectionTime"))) {
            helicobacterPyloriInfectionTimeMap = getDurationMap(jsonObject.get("helicobacterPyloriInfectionTime").toString().replaceAll("\"", ""));
        }
        info.setHelicobacterPyloriInfectionTime(helicobacterPyloriInfectionTimeMap);
        //  "helicobacterPyloriDetectionMethod": "3",幽门螺杆菌检测方法
        String helicobacterPyloriDetectionMethodMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("helicobacterPyloriDetectionMethod"))) {
            String helicobacterPyloriDetectionMethod = jsonObject.get("helicobacterPyloriDetectionMethod").toString().replaceAll("\"", "");
            helicobacterPyloriDetectionMethodMap = getHelicobacterPyloriDetectionMethodMap(helicobacterPyloriDetectionMethod, helicobacterPyloriDetectionMethodMap);
        }
        info.setHelicobacterPyloriDetectionMethod(helicobacterPyloriDetectionMethodMap);
        //  "hepatitis": "2",肝炎
        String hepatitisMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("hepatitis"))) {
            hepatitisMap = getWhetherMap(jsonObject.get("hepatitis").toString().replaceAll("\"", ""));
        }
        info.setHepatitis(hepatitisMap);
        //   "hepatitisTime": "2",疾病确诊后时间
        String hepatitisTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("hepatitisTime"))) {
            hepatitisTimeMap = getDurationMap(jsonObject.get("hepatitisTime").toString().replaceAll("\"", ""));
        }
        info.setHepatitisTime(hepatitisTimeMap);
        //"squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTract": "2",头颈部或呼吸道鳞癌
        String squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTract"))) {
            squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractMap = getWhetherMap(jsonObject.get("squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTract").toString().replaceAll("\"", ""));
        }
        info.setSquamousCellCarcinomaOfTheHeadNeckOrRespiratoryTract(squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractMap);
        //"squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractTime": "2",疾病确诊后时间
        String squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractTime"))) {
            squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractTimeMap = getDurationMap(jsonObject.get("squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractTime").toString().replaceAll("\"", ""));
        }
        info.setSquamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractTime(squamousCellCarcinomaOfTheHeadNeckOrRespiratoryTractTimeMap);
        //   "perniciousAnemia": "2",恶性贫血
        String perniciousAnemiaMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("perniciousAnemia"))) {
            perniciousAnemiaMap = getWhetherMap(jsonObject.get("perniciousAnemia").toString().replaceAll("\"", ""));
        }
        info.setPerniciousAnemia(perniciousAnemiaMap);
        //   "perniciousAnemiaTime": "2",疾病确诊后时间
        String perniciousAnemiaTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("perniciousAnemiaTime"))) {
            perniciousAnemiaTimeMap = getDurationMap(jsonObject.get("perniciousAnemiaTime").toString().replaceAll("\"", ""));
        }
        info.setPerniciousAnemiaTime(perniciousAnemiaTimeMap);
        //   "else": "2", 其它
        String elseMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("else"))) {
            elseMap = getWhetherMap(jsonObject.get("else").toString().replaceAll("\"", ""));
        }
        info.setElseStr(elseMap);
        //   "diseasName": "22",疾病名称
        info.setDiseasName(ObjectUtils.isNotEmpty(jsonObject.get("diseasName"))?jsonObject.get("diseasName").toString().replaceAll("\"", ""):"");
        //   "elseTime": "1",疾病确诊后时间
        String elseTimeMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("elseTime"))) {
            elseTimeMap = getDurationMap(jsonObject.get("elseTime").toString().replaceAll("\"", ""));
        }
        info.setElseTime(elseTimeMap);
        //  "firstDegreeRelativeHadTumor": "1", 肿瘤家族史  -  你家中有没有人得过肿瘤
        String firstDegreeRelativeHadTumorMap="";
        if (ObjectUtils.isNotEmpty(jsonObject.get("firstDegreeRelativeHadTumor"))) {
            firstDegreeRelativeHadTumorMap = getWhetherMap(jsonObject.get("firstDegreeRelativeHadTumor").toString().replaceAll("\"", ""));
        }
        info.setFirstDegreeRelativeHadTumor(firstDegreeRelativeHadTumorMap);
        // 家中得过肿瘤-亲属关系
        StringBuilder domesticRelationHadTumorMap= new StringBuilder();
        // jsonObject.get("content")判断条件补充，不为字符串“null“
        if (ObjectUtils.isNotEmpty(jsonObject.get("content"))  && !jsonObject.get("content").toString().equals("null")) {
            /**
             * "content":[
             * {"firstDegreeRelativeHadTumor":"","domesticRelation":"2","tumorName":"7","elseName":""},
             * {"firstDegreeRelativeHadTumor":"","domesticRelation":"3","tumorName":"6","elseName":""},
             * {"firstDegreeRelativeHadTumor":"","domesticRelation":"1","tumorName":"2","elseName":""}
             * ]
             * domesticRelation:亲属关系
             * tumorName：肿瘤情况
             */
            JsonElement content = jsonObject.get("content");
            JsonArray contentArray = content.getAsJsonArray();
            getDomesticRelationMap(contentArray, domesticRelationHadTumorMap);
            int lastIndex = domesticRelationHadTumorMap.lastIndexOf("|");
            if (lastIndex != -1) {
                domesticRelationHadTumorMap=new StringBuilder(domesticRelationHadTumorMap.substring(0, lastIndex));
            }
        }
        info.setDomesticRelationHadTumor(domesticRelationHadTumorMap.toString());

        // 结直肠癌风险因素自测表内容 colorectalCancerContent
        if (ObjectUtils.isNotEmpty(colorectalCancerContent)) {
            Gson gson = new Gson();
            JsonObject json = gson.fromJson(colorectalCancerContent.toString(), JsonObject.class);
            // 1、您是否曾接受过结肠镜检查
            String isCheckMap = "";
            if (ObjectUtils.isNotEmpty(json.get("isCheck"))) {
                isCheckMap = judgeWhetherMap(json.get("isCheck").toString().replaceAll("\"", ""));
            }
            info.setIsCheck(isCheckMap);
            // 2、最后一次结肠镜检查的年份
            info.setLastCheckYear(ObjectUtils.isNotEmpty(json.get("lastCheckYear"))?json.get("lastCheckYear").toString().replaceAll("\"", ""):"");
            // 3、您是否曾接受过结肠镜检查
            String isColorectalPolypsMap="";
            if (ObjectUtils.isNotEmpty(json.get("isColorectalPolyps"))) {
                isColorectalPolypsMap = judgeWhetherMap(json.get("isColorectalPolyps").toString().replaceAll("\"", ""));
            }
            info.setIsColorectalPolyps(isColorectalPolypsMap);
            // 4、您是否曾诊断炎性肠病（IBD）
            String isIBDMap="";
            if (ObjectUtils.isNotEmpty(json.get("isIBD"))) {
                isIBDMap = judgeWhetherMap(json.get("isIBD").toString().replaceAll("\"", ""));
            }
            info.setIsIBD(isIBDMap);
            // 5、诊断IBD距今时间
            info.setHasIBDTime(ObjectUtils.isNotEmpty(json.get("hasIBDTime"))?json.get("hasIBDTime").toString().replaceAll("\"", ""):"");
            // 6、您本人是否为结直肠患者
            String isColorectalPatientsMap="";
            if (ObjectUtils.isNotEmpty(json.get("isColorectalPatients"))) {
                isColorectalPatientsMap = judgeWhetherMap(json.get("isColorectalPatients").toString().replaceAll("\"", ""));
            }
            info.setIsColorectalPatients(isColorectalPatientsMap);
            // 7、您本人是否诊断有其他恶性肿瘤
            String hasOtherMalignancyMap="";
            if (ObjectUtils.isNotEmpty(json.get("hasOtherMalignancy"))) {
                hasOtherMalignancyMap = judgeWhetherMap(json.get("hasOtherMalignancy").toString().replaceAll("\"", ""));
            }
            info.setHasOtherMalignancy(hasOtherMalignancyMap);
            // 8、您的一级亲属中，是否有人患结直肠癌
            String relativesHasColorectalPatientsMap="";
            if (ObjectUtils.isNotEmpty(json.get("relativesHasColorectalPatients"))) {
                relativesHasColorectalPatientsMap = judgeWhetherMap(json.get("relativesHasColorectalPatients").toString().replaceAll("\"", ""));
            }
            info.setRelativesHasColorectalPatients(relativesHasColorectalPatientsMap);
            // 9、一级亲属中诊断肠癌的共有几人
            info.setRelativesHasColorectalPatientsNum(ObjectUtils.isNotEmpty(json.get("relativesHasColorectalPatientsNum"))?json.get("relativesHasColorectalPatientsNum").toString().replaceAll("\"", ""):"");
            // 10、诊断肠癌的一级亲属中，诊断时最小的是几岁
            info.setRelativesHasColorectalPatientsMinAge(ObjectUtils.isNotEmpty(json.get("relativesHasColorectalPatientsMinAge"))?json.get("relativesHasColorectalPatientsMinAge").toString().replaceAll("\"", ""):"");
            // 11、您是否有慢性便秘
            String hasCCMap="";
            if (ObjectUtils.isNotEmpty(json.get("hasCC"))) {
                hasCCMap = judgeWhetherMap(json.get("hasCC").toString().replaceAll("\"", ""));
            }
            info.setHasCC(hasCCMap);
            // 12、您是否有慢性腹泻
            String hasCDDMap="";
            if (ObjectUtils.isNotEmpty(json.get("hasCDD"))) {
                hasCDDMap = judgeWhetherMap(json.get("hasCDD").toString().replaceAll("\"", ""));
            }
            info.setHasCDD(hasCDDMap);
            // 13、您是否有粘液血便
            String mucousBloodyStoolMap="";
            if (ObjectUtils.isNotEmpty(json.get("mucousBloodyStool"))) {
                mucousBloodyStoolMap = judgeWhetherMap(json.get("mucousBloodyStool").toString().replaceAll("\"", ""));
            }
            info.setMucousBloodyStool(mucousBloodyStoolMap);
            // 14、您是否有慢性阑尾炎
            String hasChronicAppendicitisMap="";
            if (ObjectUtils.isNotEmpty(json.get("hasChronicAppendicitis"))) {
                hasChronicAppendicitisMap = judgeWhetherMap(json.get("hasChronicAppendicitis").toString().replaceAll("\"", ""));
            }
            info.setHasChronicAppendicitis(hasChronicAppendicitisMap);
            // 15、您是否有慢性胆囊炎
            String hasChronicCholecystitisMap="";
            if (ObjectUtils.isNotEmpty(json.get("hasChronicCholecystitis"))) {
                hasChronicCholecystitisMap = judgeWhetherMap(json.get("hasChronicCholecystitis").toString().replaceAll("\"", ""));
            }
            info.setHasChronicCholecystitis(hasChronicCholecystitisMap);
            // 16、您是否有长期遭受精神伤害
            String hasDivineDamageMap="";
            if (ObjectUtils.isNotEmpty(json.get("hasDivineDamage"))) {
                hasDivineDamageMap = judgeWhetherMap(json.get("hasDivineDamage").toString().replaceAll("\"", ""));
            }
            info.setHasDivineDamage(hasDivineDamageMap);
        }
    }

    private static String getDrinkQuantityMap(String drinkQuantity, String drinkQuantityMap) {
        switch (drinkQuantity) {
            case "1":
                drinkQuantityMap = "<2两";
                break;
            case "2":
                drinkQuantityMap = "2 ~ 5两";
                break;
            case "3":
                drinkQuantityMap = "6 ~ 10两";
                break;
            case "4":
                drinkQuantityMap = ">10两";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return drinkQuantityMap;
    }

    private static String getDrinkFrequencyMap(String drinkFrequency, String drinkFrequencyMap) {
        switch (drinkFrequency) {
            case "1":
                drinkFrequencyMap = "一周2 ~ 3次";
                break;
            case "2":
                drinkFrequencyMap = "一周4 ~ 6次";
                break;
            case "3":
                drinkFrequencyMap = "一周6次以上";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return drinkFrequencyMap;
    }

    private static String getMealTimeMap(String mealTime, String mealTimeMap) {
        switch (mealTime) {
            case "1":
                mealTimeMap = "1 ~ 10分钟";
                break;
            case "2":
                mealTimeMap = "11 ~ 20分钟";
                break;
            case "3":
                mealTimeMap = "21 ~ 30分钟";
                break;
            case "4":
                mealTimeMap = "30分钟以上";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return mealTimeMap;
    }

    private static String getPlantToothMap(String plantTooth, String plantToothMap) {
        switch (plantTooth) {
            case "1":
                plantToothMap = "无";
                break;
            case "2":
                plantToothMap = "1颗";
                break;
            case "3":
                plantToothMap = "2 ~ 4颗";
                break;
            case "4":
                plantToothMap = "3 ~ 5颗";
                break;
            case "5":
                plantToothMap = "5颗以上";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return plantToothMap;
    }

    private static String getLoseToothMap(String loseTooth, String loseToothMap) {
        switch (loseTooth) {
            case "1":
                loseToothMap = "1颗";
                break;
            case "2":
                loseToothMap = "2 ~ 4颗";
                break;
            case "3":
                loseToothMap = "3 ~ 5颗";
                break;
            case "4":
                loseToothMap = "5颗以上";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return loseToothMap;
    }

    private static void getDomesticRelationMap(JsonArray contentArray, StringBuilder domesticRelationHadTumorMap) {
        for (JsonElement element : contentArray) {
            // element判断为{}，跳出循环
            if (element.isJsonObject()){
                JsonObject jsonObject = element.getAsJsonObject();
                if (jsonObject.size() == 0 || jsonObject.entrySet().isEmpty()) {
                    continue; // 跳出当前循环
                }
            }
            JsonObject object = element.getAsJsonObject();
            String domesticRelation = object.get("domesticRelation").getAsString();
            if (ObjectUtils.isNotEmpty(domesticRelation)) {
                switch (domesticRelation){
                    case "1":
                        domesticRelationHadTumorMap.append("父母");
                        break;
                    case "2":
                        domesticRelationHadTumorMap.append("兄弟姐妹");
                        break;
                    case "3":
                        domesticRelationHadTumorMap.append("儿女");
                        break;
                    default:
                        // 处理其他未知情况
                        break;
                }
            }

            String tumorName = object.get("tumorName").getAsString();
            if (ObjectUtils.isNotEmpty(tumorName)){
                switch (tumorName){
                    case "1":
                        domesticRelationHadTumorMap.append("：肺癌").append("|");
                        break;
                    case "2":
                        domesticRelationHadTumorMap.append("：乳腺癌").append("|");
                        break;
                    case "3":
                        domesticRelationHadTumorMap.append("：结直肠癌").append("|");
                        break;
                    case "4":
                        domesticRelationHadTumorMap.append("：肝癌").append("|");
                        break;
                    case "5":
                        domesticRelationHadTumorMap.append("：胃癌").append("|");
                        break;
                    case "6":
                        domesticRelationHadTumorMap.append("：食管癌").append("|");
                        break;
                    case "7":
                        domesticRelationHadTumorMap.append("：子宫颈癌").append("|");
                        break;
                    case "8":
                        domesticRelationHadTumorMap.append("：甲状腺癌").append("|");
                        break;
                    case "9":
                        domesticRelationHadTumorMap.append("：前列腺癌").append("|");
                        break;
                    case "10":
                        domesticRelationHadTumorMap.append("：子宫体癌").append("|");
                        break;
                    case "11":
                        domesticRelationHadTumorMap.append("：口腔和咽喉肿瘤").append("|");
                        break;
                    case "12":
                        domesticRelationHadTumorMap.append("：鼻咽癌").append("|");
                        break;
                    case "13":
                        domesticRelationHadTumorMap.append("：肛门癌").append("|");
                        break;
                    case "14":
                        domesticRelationHadTumorMap.append("：胆囊癌").append("|");
                        break;
                    case "15":
                        domesticRelationHadTumorMap.append("：胰腺癌").append("|");
                        break;
                    case "16":
                        domesticRelationHadTumorMap.append("：喉癌").append("|");
                        break;
                    case "17":
                        domesticRelationHadTumorMap.append("：骨肿瘤").append("|");
                        break;
                    case "18":
                        domesticRelationHadTumorMap.append("：皮肤黑色素瘤").append("|");
                        break;
                    case "19":
                        domesticRelationHadTumorMap.append("：卵巢癌").append("|");
                        break;
                    case "20":
                        domesticRelationHadTumorMap.append("：睾丸癌").append("|");
                        break;
                    case "21":
                        domesticRelationHadTumorMap.append("：肾癌").append("|");
                        break;
                    case "22":
                        domesticRelationHadTumorMap.append("：膀胱癌").append("|");
                        break;
                    case "23":
                        domesticRelationHadTumorMap.append("：脑和中枢神经系统肿瘤").append("|");
                        break;
                    case "24":
                        domesticRelationHadTumorMap.append("：淋巴瘤").append("|");
                        break;
                    case "25":
                        domesticRelationHadTumorMap.append("：白血病").append("|");
                        break;
                    case "26":
                        domesticRelationHadTumorMap.append("：其他").append("|");
                        break;
                    default:
                        // 处理其他未知情况
                        break;
                }
            }
        }
    }

    private static String getHelicobacterPyloriDetectionMethodMap(String helicobacterPyloriDetectionMethod, String helicobacterPyloriDetectionMethodMap) {
        switch (helicobacterPyloriDetectionMethod) {
            case "1":
                helicobacterPyloriDetectionMethodMap = "快速尿素酶试验";
                break;
            case "2":
                helicobacterPyloriDetectionMethodMap = "碳 13呼气试验";
                break;
            case "3":
                helicobacterPyloriDetectionMethodMap = "碳 14呼气试验";
                break;
            case "4":
                helicobacterPyloriDetectionMethodMap = "血清抗体试验";
                break;
            case "5":
                helicobacterPyloriDetectionMethodMap = "病理诊断";
                break;
            case "6":
                helicobacterPyloriDetectionMethodMap = "粪便抗原检测";
                break;
            case "7":
                helicobacterPyloriDetectionMethodMap = "不清楚";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return helicobacterPyloriDetectionMethodMap;
    }

    private static String getDrinkString(String drink, String drinkMap) {
        switch (drink) {
            case "1":
                drinkMap = "不喝";
                break;
            case "2":
                drinkMap = "偶尔喝";
                break;
            case "3":
                drinkMap = "经常喝";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return drinkMap;
    }

    private static String getHeadwatersMap(String headwaters, String headwatersMap) {
        switch (headwaters) {
            case "1":
                headwatersMap = "地窖水、池塘水、浅井水";
                break;
            case "2":
                headwatersMap = "湖水、河水";
                break;
            case "3":
                headwatersMap = "深井水、泉水";
                break;
            case "4":
                headwatersMap = "纯净水/自来水(经处理)";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return headwatersMap;
    }

    private static String getDiastolicPressureMap(String diastolicPressure, String diastolicPressureMap) {
        switch (diastolicPressure) {
            case "1":
                diastolicPressureMap = "80mmHg以下";
                break;
            case "2":
                diastolicPressureMap = "80mmHg ~ 89mmHg";
                break;
            case "3":
                diastolicPressureMap = "90mmHg ~ 109mmHg";
                break;
            case "4":
                diastolicPressureMap = "110mmHg以上";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return diastolicPressureMap;
    }

    private static String getSystolicPressureMap(String systolicPressure, String systolicPressureMap) {
        switch (systolicPressure) {
            case "1":
                systolicPressureMap = "120mmHg以下";
                break;
            case "2":
                systolicPressureMap = "120mmHg ~ 139mmHg";
                break;
            case "3":
                systolicPressureMap = "140mmHg ~ 179mmHg";
                break;
            case "4":
                systolicPressureMap = "180mmHg以上";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return systolicPressureMap;
    }

    private static String getIncomeMap(String income, String incomeMap) {
        switch (income) {
            case "1":
                incomeMap = "1万以下";
                break;
            case "2":
                incomeMap = "1 ~ 4.9万";
                break;
            case "3":
                incomeMap = "5 ~ 9.9万";
                break;
            case "4":
                incomeMap = "10 ~ 19.9万";
                break;
            case "5":
                incomeMap = "20万以上";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return incomeMap;
    }

    private static String getPopulationMap(String population, String populationMap) {
        switch (population) {
            case "1":
                populationMap = "1人";
                break;
            case "2":
                populationMap = "2 ~ 3人";
                break;
            case "3":
                populationMap = "4 ~ 5人";
                break;
            case "4":
                populationMap = "6 ~ 7人";
                break;
            case "5":
                populationMap = "8 ~ 9人";
                break;
            case "6":
                populationMap = "10人及以上";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return populationMap;
    }

    private static String getDegreeEducationMap(String degreeEducation, String degreeEducationMap) {
        switch (degreeEducation) {
            case "1":
                degreeEducationMap = "未上过学";
                break;
            case "2":
                degreeEducationMap = "小学";
                break;
            case "3":
                degreeEducationMap = "初中";
                break;
            case "4":
                degreeEducationMap = "高中";
                break;
            case "5":
                degreeEducationMap = "大专及以上";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return degreeEducationMap;
    }

    private static String getMaritalStatusMap(String maritalStatus, String maritalStatusMap) {
        switch (maritalStatus) {
            case "1":
                maritalStatusMap = "未婚";
                break;
            case "2":
                maritalStatusMap = "已婚";
                break;
            case "3":
                maritalStatusMap = "离异";
                break;
            case "4":
                maritalStatusMap = "丧偶";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return maritalStatusMap;
    }

    private static String getDurationMap(String value) {
        String durationMap = "";
        switch (value) {
            case "1":
                durationMap = "<1年";
                break;
            case "2":
                durationMap = "1 ~ 5年";
                break;
            case "3":
                durationMap = "6 ~ 10年";
                break;
            case "4":
                durationMap = ">10年";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return durationMap;
    }

    private static String getWhetherMap(String value) {
        String map = "";
        switch (value) {
            case "1":
                map = "否";
                break;
            case "2":
                map = "是";
                break;
            case "3":
                map = "不清楚";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return map;
    }
    private static String judgeWhetherMap(String value) {
        String map = "";
        switch (value) {
            case "1":
                map = "是";
                break;
            case "2":
                map = "否";
                break;
            case "3":
                map = "不清楚";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return map;
    }

    private static String getFoodWhetherMap(String value) {
        String map = "";
        switch (value) {
            case "1":
                map = "从不";
                break;
            case "2":
                map = "很少(<2次/周)";
                break;
            case "3":
                map = "经常(>=2次/周)";
                break;
            default:
                // 处理其他未知情况
                break;
        }
        return map;
    }

    @Override
    public JsonObj importGJData(MultipartFile file, HttpServletResponse response, String userId) {
        ImportParams params = new ImportParams();
        params.setTitleRows(0);
        File tmpfile =commonImportConfig(file,userId);
        // 解析excel
        List<SysteminitImportInfo> list = ExcelImportUtil.importExcel(tmpfile, SysteminitImportInfo.class, params);
        // 数据过滤,国家来源的数据默认都是正确的，仅过滤名称为null的
        list = list.stream().filter(each -> StringUtils.isNotEmpty(each.getName()) && !Objects.equals("测试",each.getName())).collect(Collectors.toList());
        int count = 0;
        // 执行数据写入
        List<LinkedHashMap<String, Object>> failList =new ArrayList<>();
        if (!list.isEmpty()) {
            List<LinkedHashMap<String, Object>> orgList = tkmSysOrgService.listAll(new PageData());
            List<Object> orgNameList = orgList.stream().map(obj -> obj.get("org_name")).collect(Collectors.toList());
            List<CerPersonalInfo> cerPersonalInfos = cerPersonInfoService.queryAllByLimit(new CerPersonalInfo());
            // 获取extFlag
            String extFlag = sysUserService.findUserExtFlag(userId);
            // 因数据量较大，用户只需要安徽省【34】数据 ,从redis中查
            List<CityEntity> allCityInfo = new ArrayList<>();
            List<CityEntity> allAreaInfo = new ArrayList<>();
            List<CityEntity> allStreetInfo = new ArrayList<>();
            List<CityEntity> allVillageInfo = new ArrayList<>();
            getRedisByAddressCode(allCityInfo,allAreaInfo,allStreetInfo,allVillageInfo);
            List<TkmSysOrg> allOrgs = tkmSysOrgService.getAllOrgs();
            List<String> onlyScreeningIdList=new ArrayList<>();
            for (SysteminitImportInfo item : list) {
                item.setErrorFlag(1);
                String screeningId = item.getScreeningId();
                // 判断screeningId是否在onlyScreeningIdList中，不在添加onlyScreeningIdList中，在就报错
                if (onlyScreeningIdList.contains(screeningId)) {
                    failList.add(getLinkedMapByList(item,"同一个调查对象ID，系统中不能重复"));
                    item.setErrorFlag(2);
                } else {
                    onlyScreeningIdList.add(screeningId);
                }
                for (CerPersonalInfo each : cerPersonalInfos) {
                    // 1、检查screening_id是否有重复，重复的不插入
                    if (Objects.equals(item.getScreeningId(),each.getScreeningId())) {
                        failList.add(getLinkedMapByList(item,"该人员上报信息,系统中已经存在"));
                        item.setErrorFlag(2);
                    }
                }
                if (!orgNameList.contains(item.getInstitutionName())) {
                    failList.add(getLinkedMapByList(item,"机构名称,系统中不存在"));
                    item.setErrorFlag(2);
                }
            }
            // 成功的数据（过滤 errorFlag == 1成功），批量新增
            list = list.stream().filter(each -> each.getErrorFlag()==1).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(list)) {
                list.forEach(item->{
                    // 编辑cer_personal_info表数据
                    setCerPersonalInfoCommon(item,userId,extFlag,allCityInfo,allAreaInfo,allStreetInfo,allVillageInfo,allOrgs);
                    // 编辑cer_systeminit_import_info表
                    setTkmSysteminitImportInfoCommon(item,userId,extFlag);
                });
                List<CerPersonalInfo> personalInfos = list.stream().map(SysteminitImportInfo::getCerPersonalInfo).collect(Collectors.toList());
                // 对需要导入的数据进行验证
                personalInfos
                        .forEach(each -> {
                            List<String> errors = Utils.validateCerPersonalInfoData(each);
                            each.setCountrySource("1");
                            if (errors.size() > 0) {
                                each.setIsHaveError(1);
                                each.setErrorMessage(String.join("|", errors));
                            } else {
                                each.setIsHaveError(0);
                                each.setErrorMessage("");
                            }
                        });
                // 先新增cer_personal_info表
                cerPersonInfoService.addBatchPersonals(personalInfos);
                List<TkmSysteminitImportInfo> tkmSysteminitImportInfos = list.stream().map(SysteminitImportInfo::getTkmSysteminitImportInfo).collect(Collectors.toList());
                tkmSysteminitImportInfos
                        .forEach(each->{
                            //对初始数据进行校验
                            List<String> errors = Utils.validateSysteminitImportInfoData(each);
                            String njzd = each.getNjzd();
                            if (ObjectUtils.isNotEmpty(njzd)) {
                                List<String> names = Arrays.asList(njzd.split(","));
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounNames(names);
                                if (CollectionUtils.isNotEmpty(infos)) {
                                    String idsStr = infos.stream().map(TkmEndoscopeDiagnoseNounInfo::getId).collect(Collectors.joining(","));
                                    each.setNjzd(idsStr);
                                }
                            }
                            each.setDeleted(0);// 0不删除
                            each.setCountrySource("1");
                            if (errors.size() > 0) {
                                each.setIsHaveError(1);
                                each.setErrorMessage(String.join("|", errors));
                            } else {
                                each.setIsHaveError(0);
                                each.setErrorMessage("");
                            }
                        });
                // 再新增cer_systeminit_import_info表
                count = addBatchInitImport(tkmSysteminitImportInfos);
            }
        }
        // 组装表头
        List<String> headList = Arrays.asList(
                "省份",
                "城市",
                "区县",
                "乡镇",
                "村",
                "机构名称",
                "调查对象ID号",
                "姓名",
                "性别",
                "生日",
                "民族",
                "身份证号",
                "地址",
                "联系电话",
                "筛查类型",
                "随访次数",
                "内镜号",
                "是否无痛",
                "染色类别",
                "是否活检",
                "内镜诊疗日期",
                "Hp",
                "Hp检测方法",
                "图片数量",
                "内镜诊断",
                "内镜诊断医师",
                "内镜审核医师",
                "病理号",
                "病理报告日期",
                "食管病理诊断代码",
                "贲门病理诊断代码",
                "胃病理诊断代码",
                "十二指肠病理诊断代码",
                "病理诊断医师",
                "病理审核医师",
                "病理诊断",
                "导入错误原因");
        try {
            // 导出
            if (CollectionUtils.isNotEmpty(failList)) {
//                String s = ExcelUtils.downloadExcel(headList, failList, "导入失败数据导出", response, cerPersonFileInDisk);
                File downloadExcelFile = ExcelUtils.downloadExcelFile(headList, failList, "导入失败数据导出", response, cerPersonFileInDisk);
                String upload = aliyunOssService.upload(downloadExcelFile);
                HashMap<String,Object> res =new HashMap<>();
                res.put("errorFile", upload);
                String msg ="导入失败"+failList.size()+"条";
                if (count>0) {
                    msg += "，导入成功"+count+"条数据";
                }
                return JsonObj.success(res,msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonObj.error("错误数据导出失败");
        }
        return JsonObj.success("导入成功"+count+"条数据");
    }

    @Override
    public List<CerSysteminitImportInfo> getAllInitImports() {
        return cerSysteminitImportInfoMapper.getAllInitImports();
    }

    @Override
    public List<CerSysteminitImportInfo> getAllInitImportsByScreeningIds(List<String> screeningIdsByImport) {
        return cerSysteminitImportInfoMapper.getAllInitImportsByScreeningIds(screeningIdsByImport);
    }

    @Override
    public void updateBatchStatusByIds(List<String> initIds, int delStatus) {
        cerSysteminitImportInfoMapper.updateBatchStatusByIds(initIds,delStatus);
    }

    @Override
    public int addBatchInitImport(List<TkmSysteminitImportInfo> tkmSysteminitImportInfos) {
        return cerSysteminitImportInfoMapper.addBatchInitImport(tkmSysteminitImportInfos);
    }

    @Override
    public void setTkmSysteminitImportInfoCommon(SysteminitImportInfo item, String userId,String extFlag) {
        TkmSysteminitImportInfo initInfo = new TkmSysteminitImportInfo();
        // excel表中已知字段数据
        initInfo.setAddr(item.getAddr());
        initInfo.setNjzlTime(item.getNjzlTime());
        // 是否无痛 -> 转成字典中的code值【校验时，已经匹配】
        initInfo.setAche(item.getAche());
        // 染色类别 -> 转成字典中的code值【校验时，已经匹配】
        initInfo.setDye(item.getDye());
        initInfo.setNjNum(item.getNjNum());
        initInfo.setPicNums(item.getPicNums());
        // 是否活检 -> 转成字典中的code值 【校验时，已经匹配】
        initInfo.setIsHj(item.getIsHj());
        // Hp 检测结果 -> 转成字典中的code值【校验时，已经匹配】
        initInfo.setHp(item.getHp());
        // Hp检测方法 -> 转成字典中的code值【校验时，已经匹配】
        initInfo.setHpjcjg(item.getHpjcjg());
        // 内镜诊断 -> 转成字典中的code值
        initInfo.setNjzd(item.getNjzd());
        initInfo.setNjStaff(item.getNjStaff());
        initInfo.setVerifyStaff(item.getVerifyStaff());
        initInfo.setBlNum(item.getBlNum());
        // 病理诊断：直接录入
        initInfo.setBlzd(item.getBlzd());
        // 食管\贲门\胃病\十二指肠病理诊断代码直接录入
        initInfo.setSgblCode(item.getSgblCode());
        initInfo.setBmblCode(item.getBmblCode());
        initInfo.setWblCode(item.getWblCode());
        initInfo.setSezcCode(item.getSezcCode());
        initInfo.setBlzdStaff(item.getBlzdStaff());
        initInfo.setBlshStaff(item.getBlshStaff());
        initInfo.setBlbgTime(item.getBlbgTime());
        initInfo.setScreeningType(null);
        if (ObjectUtils.isNotEmpty(item.getScreeningType())) {
            String screeningType = item.getScreeningType().trim();
            switch (screeningType) {
                case "1":
                case "2":
                    initInfo.setScreeningType(Integer.parseInt(screeningType) - 1);
                    break;
                case "初筛":
                    initInfo.setScreeningType(0);
                    break;
                case "随访":
                    initInfo.setScreeningType(1);
                    break;
            }
        }
        /* 求出未知数据 */
        // 是否发布【is_publish】
        initInfo.setIsPublish(0);
        // 是否有错误【is_have_error】【校验时，已经匹配】
//        initInfo.setIsHaveError(0);
        // 错误信息【error_message】【校验时，已经匹配】
        // 数据上报者【create_by】
        initInfo.setCreateBy(userId);
        // 版本号【version】“1”
        initInfo.setVersion(1);
        // 拓展字段1【ext_flag】
        initInfo.setExtFlag(extFlag);
        // 拓展字段2【ext_flag_2】？(默认食管，贲门,胃和治疗，随访数据为空)
        initInfo.setExtFlag2("0|0|0");
        // 是否高危【is_dangerous】“1”不高危
        initInfo.setIsDangerous(1);
        //调查对象ID号【screening_id】
        initInfo.setScreeningId(item.getScreeningId());
        //是否超时【is_uplpad_timeout】“0”未超时
        initInfo.setIsUplpadTimeout(0);
        // 是否已上报【is_uploaded】“0”未上报
        initInfo.setIsUploaded(0);
        // 基础人员信息ID【person_id】
        initInfo.setPersonId(item.getCerPersonalInfo().getId());
        initInfo.setId(get32UUID());
        // 校验规则时，冗余字段
        initInfo.setName(item.getName());
        initInfo.setSex(item.getSex());
        initInfo.setSfz(item.getIdCard());
        initInfo.setPhone(item.getPhone());
        item.setTkmSysteminitImportInfo(initInfo);
    }

    @Override
    public void setCerPersonalInfoCommon(SysteminitImportInfo item, String userId,String extFlag,
                                          List<CityEntity> allCityInfo,List<CityEntity> allAreaInfo,
                                          List<CityEntity> allStreetInfo,List<CityEntity> allVillageInfo,List<TkmSysOrg> allOrgs ) {
        CerPersonalInfo cerPersonalInfo = new CerPersonalInfo();
        cerPersonalInfo.setId(get32UUID());
        // excel表中已知字段数据
        cerPersonalInfo.setName(item.getName());
        cerPersonalInfo.setIdCard(item.getIdCard());
        cerPersonalInfo.setSex(item.getSex());
        cerPersonalInfo.setNationName(item.getNationName());
        cerPersonalInfo.setProvinceName(item.getProvinceName());
        cerPersonalInfo.setCityName(item.getCityName());
        cerPersonalInfo.setDistrictName(item.getDistrictName());
        cerPersonalInfo.setInstitutionName(item.getInstitutionName());
        cerPersonalInfo.setCountyName(item.getCountyName());
        cerPersonalInfo.setVillageName(item.getVillageName());
        cerPersonalInfo.setAddr(item.getAddr());
        cerPersonalInfo.setPhone(item.getPhone());
        cerPersonalInfo.setBirthday(item.getBirthday());
        cerPersonalInfo.setScreeningId(item.getScreeningId());
        /* 求出未知数据 */
        // 民族编码【nation_code】
        cerPersonalInfo.setNationCode(ObjectUtils.isEmpty(item.getNationName())?"":Nation.getCodeByDescription(item.getNationName()));
        // 机构编号【institution_id】
        allOrgs.forEach(each->{
            if (Objects.equals(each.getOrgName(),item.getInstitutionName())) {
                cerPersonalInfo.setInstitutionId(String.valueOf(each.getId()));
            }
        });
        cerPersonalInfo.setProvinceId("34");
        // 省编号【province_id】
//        allProvincesInfo.forEach(each->{
//            if (Objects.equals(each.getName(),item.getProvinceName())) {
//                cerPersonalInfo.setProvinceId(each.getCode());
//            }
//        });
        // 市编号【city_id】
        allCityInfo.forEach(each->{
            if (Objects.equals(each.getName(),item.getCityName())) {
                cerPersonalInfo.setCityId(each.getCode());
            }
        });
        // 区编号【district_id】
        allAreaInfo.forEach(each->{
            if (Objects.equals(each.getName(),item.getDistrictName())) {
                cerPersonalInfo.setDistrictId(each.getCode());
            }
        });
        // 乡镇编号【county_id】
        allStreetInfo.forEach(each->{
            if (Objects.equals(each.getName(),item.getCountyName())) {
                cerPersonalInfo.setCountyId(each.getCode());
            }
        });
        // 村编号【village_id】
        allVillageInfo.forEach(each->{
            if (Objects.equals(each.getName(),item.getVillageName())) {
                cerPersonalInfo.setVillageId(each.getCode());
            }
        });
        // 数据上报者【create_by】
        cerPersonalInfo.setCreateBy(userId);
        // 拓展字段【ext_flag】
        cerPersonalInfo.setExtFlag(extFlag);
        // 是否有错误【is_have_error】“0”
        // 错误信息【error_message】
        item.setCerPersonalInfo(cerPersonalInfo);
    }

    @Override
    public LinkedHashMap<String, Object> getLinkedMapByList(SysteminitImportInfo info,String importError) {
        LinkedHashMap<String, Object> map=new LinkedHashMap<>();
        map.put("provinceName",info.getProvinceName());
        map.put("cityName",info.getCityName());
        map.put("districtName",info.getDistrictName());
        map.put("countyName",info.getCountyName());
        map.put("villageName",info.getVillageName());
        map.put("institutionName",info.getInstitutionName());
        map.put("screeningId",info.getScreeningId());
        map.put("name",info.getName());
        map.put("sex",info.getSex());
        map.put("birthday",info.getBirthday());
        map.put("nationName",info.getNationName());
        map.put("idCard",info.getIdCard());
        map.put("addr",info.getAddr());
        map.put("phone",info.getPhone());
        map.put("screeningType",info.getScreeningType());
        map.put("number",info.getNumber());
        map.put("njNum",info.getNjNum());
        map.put("ache",info.getAche());
        map.put("dye",info.getDye());
        map.put("isHj",info.getIsHj());
        map.put("njzlTime",info.getNjzlTime());
        map.put("Hp",info.getHp());
        map.put("hpjcff",info.getNjzd());
        map.put("picNums",info.getPicNums());
        map.put("njzd",info.getNjzd());
        map.put("njStaff",info.getNjStaff());
        map.put("verifyStaff",info.getVerifyStaff());
        map.put("blNum",info.getBlNum());
        map.put("blbgTime",info.getBlbgTime());
        map.put("sgblCode",info.getSgblCode());
        map.put("bmblCode",info.getBmblCode());
        map.put("wblCode",info.getWblCode());
        map.put("sezcCode",info.getSezcCode());
        map.put("blzdStaff",info.getBlzdStaff());
        map.put("blshStaff",info.getBlshStaff());
        map.put("blzd",info.getBlzd());
        map.put("importError",importError);
        return map;
    }

    /**
     * yyyyMMdd ===> yyyy-MM-dd
     */
    private String timeFormat (String yyyyMMdd) {
        try {
            LocalDate date = LocalDate.parse(yyyyMMdd, DateTimeFormatter.ofPattern("yyyyMMdd"));
            return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        } catch (Exception e) {
            return yyyyMMdd;
        }
    }
}
